#!/bin/bash
#========================================================================
# Author: YSLin
# Email: 
# File Name: getTheLast6Lines.sh
# Description: 
#   
# Edit History: 
#   2011-02-24    File created.
#========================================================================

#[1] : set label loop
#[2] : when read the last line of the file, the quit 
#[3] : read 5 line into pattern space, then 'D' to delete the first line from pattern space.
#[4] : 'N' read next line into pattern space
#[5] : 'b' branch to loop label

#Steps [3] and [4] are used to slide the window:
#   command `D' of Step [3] deletes the first line of PS.
#   sed then branches to Step [1].
#   Steps [2] and [3] are not performed since the conditions are not satisfied.
#   Step [4] joins the next line to the end of PS.
sed ' 
:loop
$q
/^\([^\n]*\n\)\{5\}/D   
N
b loop' line.txt


#The loop consists of Steps [1] thru [3] repeats until PS has 6 lines.
#Then Steps [4] and [2] are used to slide the window:
#   command `D' of Step [4] deletes the first line of PS.
#   sed then branches to Step [1].
#   Step [2] joins the next line to the end of PS.
#   Step [3] are not performed since the condition is not satisfied.
#[3] : if pattern space doesn't contains 5 lines, back to the label loop
#[4] : if not read the last line, delete the first line of pattern space, then restart the script
sed '
:loop
N
/^\([^\n]*\n\)\{5\}/!b loop
$!D' line.txt
